var express = require('express');
var router = express.Router();

const AccessoryRequest = require('../../models/newmodels/accessoryRequest');


// 添加一个新的申请配件请求
router.post('/accessoryRequests', async (req, res) => {
  try {
    const { machineId } = req.body;
    console.log(req.body);

    if (!machineId) {
      return res.status(400).json({ code: 400, msg: '参数不合法', data: null });
    }
    const newAccessoryRequest = new AccessoryRequest({
      machineId
    });
    const savedRequest = await newAccessoryRequest.save();
    res.json({ code: 200, msg: '申请配件请求创建成功', data: savedRequest });
  } catch (err) {
    console.error('Error creating accessory request:', err);
    res.status(500).json({ code: 500, msg: '服务器内部错误', data: err.message });
  }
});

// 获取所有申请配件请求
// router.get('/accessoryRequests', async (req, res) => {
//   try {
//     const accessoryRequests = await AccessoryRequest.find().populate({
//       path: 'machineId'
//     });
//     res.json({ code: 200, msg: '查询成功', data: accessoryRequests });
//   } catch (err) {
//     res.status(500).json({ code: 500, msg: '服务器内部错误', data: err.message });
//   }
// });

router.get('/accessoryRequests', async (req, res) => {
  try {
    const { status } = req.query; // 获取查询参数
    const query = {};

    if (status) {
      query.status = status; // 如果有status参数，则添加到查询条件中
    }

    const accessoryRequests = await AccessoryRequest.find(query).populate({
      path: 'machineId'
    });

    res.json({ code: 200, msg: '查询成功', data: accessoryRequests });
  } catch (err) {
    console.error('Error querying accessory requests:', err);
    res.status(500).json({ code: 500, msg: '服务器内部错误', data: err.message });
  }
});

// 修改申请配件请求的状态
router.put('/updateaccessoryRequests', async (req, res) => {
  try {
    const { _id, requestNumber } = req.body;
    console.log();


    if (!_id || !requestNumber) {
      return res.status(400).json({ code: 400, msg: '参数不合法', data: null });
    }

    const updatedRequest = await AccessoryRequest.findOneAndUpdate(
      { _id },
      { requestNumber, status: '已申请', updatedAt: new Date() },
      { new: true, runValidators: true }
    );

    if (!updatedRequest) {
      return res.status(404).json({ code: 404, msg: '申请配件请求不存在', data: null });
    }

    res.json({ code: 200, msg: '更新成功', data: updatedRequest });
  } catch (err) {
    console.error('Error updating accessory request:', err);
    res.status(500).json({ code: 500, msg: '服务器内部错误', data: err.message });
  }
});



module.exports = router;